<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 400px;
            margin: 50px auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 12px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
            transition: background 0.3s;
        }
        button:hover {
            background: #0056b3;
        }
        .message {
            margin-top: 15px;
            text-align: center;
            min-height: 20px; /* 防止按钮跳动 */
        }
        .error {
            color: #dc3545;
        }
        .success {
            color: #28a745;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>用户登录</h2>
        <input type="text" id="username" placeholder="用户名">
        <input type="password" id="password" placeholder="密码">
        <button onclick="login()">登录</button>
        <div id="message" class="message"></div>
        <p style="text-align: center; margin-top: 15px;">
            <a href="index.html">返回首页</a> | <a href="register.html">注册账号</a>
        </p>
    </div>
    <script>
        // 后端服务基础地址（确保与后端启动地址一致）
        const API_BASE_URL = 'http://127.0.0.1:5000';
        
        function login() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const msgEl = document.getElementById('message');

            // 输入验证
            if (!username) {
                showMessage(msgEl, '请输入用户名', 'error');
                return;
            }
            if (!password) {
                showMessage(msgEl, '请输入密码', 'error');
                return;
            }
            if (password.length < 6) {
                showMessage(msgEl, '密码长度不能少于6位', 'error');
                return;
            }

            // 显示加载状态
            showMessage(msgEl, '登录中...', '');

            // 发送登录请求
            fetch(`${API_BASE_URL}/login`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json'
                },
                credentials: 'include', // 携带跨域凭证
                body: JSON.stringify({
                    username,
                    password
                })
            })
            .then(res => {
                // 处理HTTP错误状态
                if (!res.ok) {
                    return res.json().then(data => {
                        // 优先使用后端返回的错误信息
                        throw new Error(data.error || `请求失败，状态码: ${res.status}`);
                    });
                }
                return res.json();
            })
            .then(data => {
                if (data.authenticated) {
                    // 存储用户信息（不含密码）
                    localStorage.setItem('userInfo', JSON.stringify(data.user_info));
                    showMessage(msgEl, '登录成功，正在跳转...', 'success');
                    // 1秒后跳转到首页
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 1000);
                } else {
                    showMessage(msgEl, data.error || '用户名或密码错误', 'error');
                }
            })
            .catch(err => {
                console.error('登录错误详情:', err);
                // 提取错误信息中的具体内容
                const errorMessage = err.message.includes(':') 
                    ? err.message.split(': ')[1] 
                    : err.message;
                showMessage(msgEl, `登录失败：${errorMessage}`, 'error');
            });
        }

        // 显示消息的工具函数
        function showMessage(element, text, type) {
            element.textContent = text;
            element.className = 'message'; // 重置样式
            if (type) {
                element.classList.add(type);
            }
        }

        // 监听回车键提交
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                login();
            }
        });
    </script>
</body>
</html>